from django.http import JsonResponse, HttpResponse, Http404
from rest_framework.parsers import JSONParser
from .serializers import UserInfoSerializer
from .models import UserInfo

from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import status
from rest_framework.views import APIView


class UserListView(APIView):
    # 设置模型类
    model = UserInfo
    serializer =  UserInfoSerializer
    def get(self, request, format=None):
        # 获取信息
        # 查询所有用户信息
        users = self.model.objects.all()
        # 创建序列化器对象
        ser = self.serializer(users, many=True)

        result = {
            "data": ser.data,
            "code": 200,
            "message": "ok",
        }
        return Response(result, status=status.HTTP_200_OK)

    def post(self, request, format=None):
        # 添加一条信息
        ser = self.serializer(data=request.data)
        if ser.is_valid():
            ser.save()
            data = {'code': 201, "data": ser.data, "message": "ok"}
            return Response(data, status=status.HTTP_201_CREATED)
        else:
            data = {'code': 400, "message": ser.errors}
            return Response(data, status=status.HTTP_400_BAD_REQUEST)


class UserDetailView(APIView):
    model = UserInfo
    serializer =  UserInfoSerializer
    def get_object(self, id):
        try:
            return self.model.objects.get(id=id)
        except Exception as e:
            raise Http404()

    def get(self, request, id, format=None):
        obj = self.get_object(id)
        ser = self.serializer(obj)
        data = {'code': 200, "data": ser.data, "message": "ok"}
        return Response(data, status=status.HTTP_200_OK)

    def delete(self, request, id, format=None):
        obj = self.get_object(id)
        obj.delete()
        data = {'code': 204, "message": "删除成功"}
        return Response(data, status=status.HTTP_204_NO_CONTENT)

    def put(self, request, id, format=None):
        obj = self.get_object(id)
        ser = self.serializer(instance=obj, data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({'code': 200, "data": ser.data, "message": "ok"}, status=status.HTTP_200_OK)
        else:
            return Response({'code': 400, "message": ser.errors}, status=status.HTTP_400_BAD_REQUEST)
